import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/load_my_goods.dart';

class OrderListPage extends StatefulWidget {
  const OrderListPage({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _OrderListPageState createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage>
    with SingleTickerProviderStateMixin {
  List<OrderModel> orderList = [];

  void refreshData() {
    setState(() {
      orderList = SpUtil.getObjList<OrderModel>(Constant.orderList,
              (v) => OrderModel.fromJson(v as Map<String, dynamic>)) ??
          [];
      orderList = orderList.reversed.toList();
    });
  }

  @override
  void initState() {
    super.initState();
    refreshData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Order List'),
        backgroundColor: Color(SpUtil.getInt(Constant.mainColor) ?? MyColor.mainColor.value),
      ),
      body: EasyRefresh(
        onRefresh: () {
          refreshData();
        },
        child: ListView(
          children: List.generate(orderList.length,
              (index) => _buildEveryOrderItem(orderList[index])),
        ),
      ),
    );
  }

  Widget _buildEveryOrderItem(OrderModel orderModel) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      margin: const EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          /// orderNo
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                '#${orderModel.orderNo}',
                style: const TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 16,
                    fontWeight: FontWeight.w500),
              ),
            ],
          ),
          const SizedBox(
            height: 16,
          ),

          if (orderModel.goodList == null ||
              orderModel.goodList?.isEmpty == true) ...[
            /// order Default page
            const SizedBox(),
          ]

          /// good info
          else if (orderModel.goodList?.length == 1) ...[
            /// single
            _productInfo(orderModel.goodList!, orderModel.totalPrice ?? 0,
                orderModel.createTime ?? ''),
          ] else ...[
            /// multiple
            _productsInfo(orderModel.goodList!, orderModel.totalPrice ?? 0,
                orderModel.createTime ?? ''),
          ],
          const SizedBox(
            height: 16,
          ),
        ],
      ),
    );
  }

  ///multiple goods
  Widget _productsInfo(List<GoodModel> list, double price, String createTime) {
    return SizedBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          SizedBox(
            height: 100,
            child: Row(
              children: [
                Expanded(
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    padding: EdgeInsets.zero,
                    itemBuilder: (_, index) {
                      return _productImage(list[index].localUrl ?? '');
                    },
                    itemCount: list.length,
                  ),
                ),
                const SizedBox(
                  width: 32,
                ),
                Text(
                  'X${list.fold(0, (previousValue, element) {
                    return (element.num ?? 0) + previousValue;
                  })}',
                  style: const TextStyle(
                    height: 1,
                    color: Color(0xFF666666),
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                createTime,
                style: const TextStyle(
                  height: 1,
                  color: Color(0xFF999999),
                  fontSize: 10,
                ),
              ),
              Text(
                'Total Value:\$$price',
                style: const TextStyle(
                  height: 1,
                  color: Color(0xFF333333),
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// single good - goods info
  Widget _productInfo(List<GoodModel> list, double price, String createTime) {
    final GoodModel model = list.first;
    return Column(
      children: [
        Row(
          children: [
            _productImage(model.localUrl ?? ''),
            const SizedBox(
              width: 16,
            ),
            _productDetailInfo(model, price, createTime),
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              createTime,
              style: const TextStyle(
                height: 1,
                color: Color(0xFF999999),
                fontSize: 10,
              ),
            ),
            Text(
              'Total Value:\$$price',
              style: const TextStyle(
                height: 1,
                color: Color(0xFF333333),
                fontSize: 14,
              ),
            ),
          ],
        )
      ],
    );
  }

  /// picture
  Widget _productImage(String pictureUrl) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Image.asset(
          pictureUrl,
          width: 90,
          height: 90,
        ),
      ),
    );
  }

  /// single good detail
  Widget _productDetailInfo(GoodModel model, double price, String createTime) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            height: 5,
          ),
          SizedBox(
            child: Text(
              model.goodName ?? '',
              style: const TextStyle(
                height: 1,
                color: Color(0xFF333333),
                fontSize: 14,
              ),
            ),
          ),
          const SizedBox(
            height: 12,
          ),
          Row(
            children: [
              Expanded(
                  child: Text(
                'X ${model.num ?? 0}',
                textAlign: TextAlign.end,
                style: const TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 12,
                ),
              )),
            ],
          ),
          const SizedBox(
            height: 5,
          ),
        ],
      ),
    );
  }
}
